from flask import render_template, request, url_for, redirect, flash
from myweb import app, db
from myweb.models import Customer


@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        gyid = request.form['gyid']
        customers = [Customer.query.get(gyid)]
        return render_template('index.html', customers=customers)
    customers = Customer.query.all()
    return render_template('index.html', customers=customers)


@app.route('/Customer/edit/<int:customer_id>', methods=['GET', 'POST'])

def edit(customer_id):
    customer = Customer.query.get_or_404(customer_id)
    if request.method == 'POST':
        name = request.form['name']
        sl = request.form['sl']
        lj = request.form['lj']
        addr = request.form['addr']
        customer.title = name
        customer.detail = sl
        customer.time = lj
        customer.statu = addr
        db.session.commit()
        flash('修改成功')
        return redirect(url_for('index'))

    return render_template('edit.html', customer=customer)


@app.route('/Customer/delete/', methods=['POST', 'GET'])
def delete():
    if request.method == "POST":
        form_id = request.form.get('form_id')
        print(form_id)
        if form_id == "1":
            customer_id = request.form['gyid']
            print('customer_id', customer_id)
            customer = Customer.query.get(customer_id)
            if customer:
                print('customer:',customer.id)
                return render_template('delete.html', customer=customer)
            else:
                flash('该事项不存在或已经删除！')
                return redirect(url_for('delete'))
        elif form_id == '2':
            customer_id = request.form['deleid']
            print('deleid=',customer_id)
            customer = Customer.query.get(customer_id)
            print('getdeleid=', customer_id)
            db.session.delete(customer)
            db.session.commit()
            flash('删除成功')
            return redirect(url_for('index'))
    return render_template('delete.html', customer=None)


@app.route('/Customer/add/', methods=['GET', 'POST'])
def add():
    if request.method == 'POST':
        formdata = request.form
        newcu = Customer(title=formdata['name'], detail=formdata['sl'], time=formdata['lj'],statu=0)
        db.session.add(newcu)
        db.session.commit()
        flash('add success', 'success')
        return redirect(url_for('index'))
    return render_template('add.html')


